package com.bianmaba.services.datacollection;

import com.bianmaba.beans.datacollection.ExecuteLog;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;

@Component
@Log4j2
@Scope("singleton")
public class ExecuteLogRecorder implements Runnable {
    @Autowired
    private IExecuteLogService service;
    //TODO 此处需要修改为REDIS缓存日志信息，以免日志丢失
    private final LinkedBlockingDeque<ExecuteLog> DEQUE = new LinkedBlockingDeque();


    @Override
    public void run() {
        log.info("日志写入器开始运行");
        while (true) {
            try {
                ExecuteLog log = this.DEQUE.takeFirst();
                service.saveAndFlush(log);
            } catch (InterruptedException e) {
                log.debug("任务日志写入器终止运行。");
                break;
            } catch (Exception e) {
                log.error("运行日志保存出现异常。", e);
            }
        }
    }

    public void put(ExecuteLog executeLog) {
        if (StringUtils.isNotEmpty(executeLog.getLog())) {
            if (StringUtils.isEmpty(executeLog.getTaskInstance().getId())) {
                log.error("执行日志缺少任务实例编号，无法记录。");
                return;
            }
            DEQUE.offer(executeLog);
        }
    }

    public void put(List<ExecuteLog> logs) {
        if (logs != null && !logs.isEmpty()) {
            for (ExecuteLog executeLog : logs) {
                if (StringUtils.isEmpty(executeLog.getTaskInstance().getId())) {
                    log.error("执行日志缺少任务实例编号，无法记录。");
                    continue;
                }
                if (StringUtils.isNotEmpty(executeLog.getLog())) {
                    DEQUE.offer(executeLog);
                }
            }
        }
    }
}
